package com.shudingke.controller;


import com.alibaba.druid.util.StringUtils;
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import com.shudingke.domain.User;
import com.shudingke.service.IUserService;

import com.shudingke.utils.FileNameUtils;
import com.shudingke.utils.RandomCodeUtils;
import darabonba.core.client.ClientOverrideConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ${author}
 * @since 2022-06-29
 */
@Controller
@RequestMapping("/user")
public class UserController {
    //获取redis数据库连接对象
    @Autowired
    StringRedisTemplate redisTemplate;
    
    
    @Autowired
    IUserService service;

    //登录
    @RequestMapping("/login")
    @ResponseBody
    public int login(String username, String password, String box, Model model,
                      HttpServletRequest req, HttpServletResponse resp){
        User user = new User();
        //设置查询条件
        QueryWrapper<User> qw = new QueryWrapper();
        qw.eq("username",username).eq("password",password);
        
        
        
        //如果redis数据库里面能查到直接拿，如果不能就从数据库里面拿，然后存储到redis中
        User user1 = user.selectOne(qw);
        
        
        
        if (user1 != null){
            //把这个人的用户id（唯一标识）保存到session域
            req.getSession().setAttribute("uid",user1.getUid());
            req.getSession().setAttribute("username",user1.getUsername());
            //检查是否勾选了checkbox
            if ("true".equals(box)){
                Cookie cookie1 = new Cookie("username",username);
                cookie1.setPath("/");
                cookie1.setMaxAge(6000);
                Cookie cookie2 = new Cookie("password",password);
                cookie2.setPath("/");
                cookie2.setMaxAge(6000);
                resp.addCookie(cookie1);
                resp.addCookie(cookie2);
            }
            return 1;
        }
        return 0;
    }

    //注册
    //注册成功返回1
    @RequestMapping("/reg")
    @ResponseBody
    public int reg(String username,String password){
        //是否封号
        String isDelete = "否";
        //创建时间
        LocalDateTime regTime = LocalDateTime.now();
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setIsDelete(isDelete);
        user.setRegTime(regTime);
        boolean b = service.save(user);
        if (b){
            return 1;
        }else {
            return 0;
        }
        
    }
    
    //检查用户名是否已经存在
    //返回1代表用户已经存在了
    @RequestMapping("/check")
    @ResponseBody
    public int checkUsername(String username){
        if (StringUtils.isEmpty(username)){
            return 0;
        }else {
            QueryWrapper<User> qw = new QueryWrapper<>();
            qw.eq("username",username);
            User user = service.getOne(qw);
            if (user != null){
                return 1;
            }else {
                return 0;
            }
        }
    }
    
    
    
    //修改密码
    @ResponseBody
    @RequestMapping("/changePassword")
    public Map changePassword(HttpServletRequest req,String oldPassword,String newPassword,String confirmPassword){
        Map map = new HashMap();
        
        if (StringUtils.isEmpty(oldPassword)){
            map.put("state",400);
            map.put("message","原密码不能为空！");
            return map;
        }
        if (StringUtils.isEmpty(newPassword)){
            map.put("state",400);
            map.put("message","新密码不能为空！");
            return map;
        }
        if (StringUtils.isEmpty(confirmPassword)){
            map.put("state",400);
            map.put("message","请确认密码！");
            return map;
        }
        String uuid = req.getSession().getAttribute("uid").toString();
        User user = new User();
        user.setUid(Integer.parseInt(uuid));
        User user1 = user.selectById();
        if (user1.getPassword().equals(oldPassword)){
            //对上号了
            if (confirmPassword.equals(newPassword)){
                user.setPassword(newPassword);
                user.updateById();
                map.put("state",200);
                map.put("message","修改成功！");
                return map;
            }else {
                map.put("state",400);
                map.put("message","请确认密码！");
                return map;
            }
        }else {
            map.put("state",400);
            map.put("message","原始密码输入有误！");
            return map;
        }
    }
    
    
    @RequestMapping("/update")
    @ResponseBody
    public User update(@RequestBody User user){
        user.updateById();
        return user;
    }
    
    
    @RequestMapping("/userData")
    @ResponseBody
    public User userData(HttpServletRequest req){
        String uuid = req.getSession().getAttribute("uid").toString();
        User user = new User();
        user.setUid(Integer.parseInt(uuid));
        User user1 = user.selectById();
        return user1;
    }
    
    
    
    //上传头像
    //MultipartFile文件上传类型
    @RequestMapping("/fileUpload")
    public String fileUpload(Model model,MultipartFile[] upload, HttpServletRequest req) throws Exception {
        String uuid = req.getSession().getAttribute("uid").toString();
        /*
         * 1.指定上传文件的目录
         * 2.检查该目录是否存在
         * 3.获取文件名(改上传文件名)20220623xxxxx
         * 4.上传
         * */

        //指定上传目录
        String realPath = "D:\\JAVA\\maven\\desktopStoreSystem\\target\\classes\\static\\images\\index\\";


        //检查上传目录是否存在
        File file = new File(realPath);
        if(!file.exists()) {
            file.mkdir();
        }


        for(MultipartFile mf : upload) {
            if(mf.getSize()>0) {
                //改变原始文件名
                String oldName = mf.getOriginalFilename();
                String newName = FileNameUtils.changeName(oldName);
                //上传
                mf.transferTo(new File(realPath + uuid + newName));
                model.addAttribute("avatar",uuid + newName);
                User user = new User();
                user.setUid(Integer.parseInt(uuid));
                user.setAvatar(uuid + newName);
                user.updateById();
            }
        }
        
        //
        return "upload";
    }
    
    
    //前往上传头像界面
    @RequestMapping("/gotoUpload")
    public String gotoUpload(Model model,HttpServletRequest req){
        String uuid = req.getSession().getAttribute("uid").toString();
        User user = new User();
        user.setUid(Integer.parseInt(uuid));
        User user1 = user.selectById();
        String avatar = user1.getAvatar();
        model.addAttribute("avatar",avatar);
        return "upload";
    }
    
    
    
    
    //获取验证码
    @RequestMapping("/getCode")
    @ResponseBody
    public String getCode(HttpServletRequest req) throws Exception {


        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId("LTAI5tCQgcrdfrMfxUFWYPNp")
                .accessKeySecret("DuCwUwj4veufL8Lo1oHdYqbVhEAiMi")
                .build());
        AsyncClient client = AsyncClient.builder()
                .region("cn-hangzhou")
                .credentialsProvider(provider)
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                .setEndpointOverride("dysmsapi.aliyuncs.com")
                )
                .build();
        Integer randomCodes = RandomCodeUtils.getRandomCodes(4);
        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .signName("阿里云短信测试")
                .templateCode("SMS_154950909")
                .phoneNumbers("15827136305")
                .templateParam("{code:" + randomCodes + "}")
                .build();

        CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
        SendSmsResponse resp = response.get();
        System.out.println(new Gson().toJson(resp));
        client.close();
        
        //把生成的验证码存储到redis中  存60s
        redisTemplate.opsForValue().set("code",randomCodes + "",60, TimeUnit.SECONDS);
       
        return "111";
    }
    
    
    
    //验证码登录的方法
    @RequestMapping("/codeLogin")
    @ResponseBody
    public int codeLogin(HttpServletRequest req,String phone,String code){
        User user = new User();
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("phone",phone);
        User user1 = user.selectOne(qw);
        if (user1 == null){
            return 400;
        }
        if (user1.getPhone().equals(phone)){
            //拿出来的code
            String code1 = redisTemplate.opsForValue().get("code");
            if (code1 == null){
                return 300;
            }
            if (code1.equals(code)){
                req.getSession().setAttribute("uid",user1.getUid());
                return 200;
            }else {
                return 400;
            }
        }else {
            return 400;
        }
    }
}

